﻿using CKS.PLC.Core.Core;
using McProtocolNext;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZR.Model.Models.ProductionControl;

namespace ImportPlcPointPosition.Controls
{
    public partial class McClientControl : BaseUserControl
    {
        public McClientControl()
        {
            InitializeComponent();
            this.Load += McClientControl_Load;
           
        }

      

        McProtocol plcSession;
        private  void McClientControl_Load(object sender, EventArgs e)
        {
            
        }

        public async Task StartAsync()
        {
            McProtocolConfig config = new McProtocolConfig()
            {
                ProtocolFrame = "MC3E",
                Ip = CurrentPlc.PlcAddress,
                Port = (short)CurrentPlc.PlcPort
            };
            plcSession?.Dispose();
            plcSession = new McProtocol(config);
            bool isConnected = await plcSession.TryReconnectToPlcAsync();
            panel1.Enabled = isConnected;
            AddLog($"连接状态:{isConnected}");
        }

        /// <summary>
        /// 当前PLC信息
        /// </summary>
        public PlcConfig CurrentPlc = null;
        private void btnClear_Click(object sender, EventArgs e)
        {
            txtLog.Clear();
        }

        void AddLog(string msg)
        {
            StringBuilder sb = new StringBuilder(msg);
            sb.Append("\n");
            this.txtLog.AppendText(sb.ToString());
            
        }
        private async void btnTest_Click(object sender, EventArgs e)
        {
            txtLog.Clear();
            var bytes = await plcSession.ReadDeviceBlockAsync(PlcDeviceType.D, 9500, 20);
            var wordLength = 10;
            var words = new short[wordLength];

            for (int i = 0; i < wordLength; i++)
            {
                // words[i] = (short)(bytes[i * 2] | (bytes[i * 2 + 1]) << 8);
                words[i] = BitConverter.ToInt16(bytes, i * 2);
                AddLog($"{words[i]}");
            }

            var boolBytes = bytes.Skip(10 * 2).ToArray();
            int boolLenth = 160;
            bool[] bits = new bool[boolLenth];
            for (int i = 0; i < boolLenth; i++)
            {
                bits[i] = (boolBytes[i / 8] >> (i % 8) & 1) == 1;
                AddLog($"{bits[i]}");
            }
            //处理心跳信号
            var heartValue = words[0];
            

            
        }
    }
}
